/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package meuteste;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Calendar;
import javax.swing.Timer;

/**
 *
 * @author Laboratório
 */
public class ThreadReqDados implements Runnable {

    private boolean requisitarDados = false;
    private boolean passou60Seg = false;
    private Timer timer1, timer2;
    private PortaSerial portaSerial;
    private boolean terminouRequisicao = true;
    

    public ThreadReqDados(PortaSerial portaSerial) {
        timer1 = new Timer(60000 - (Calendar.getInstance().get(Calendar.SECOND) * 1000), new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                passou60Seg = true;
                run();
                timer1.stop();
                timer2.start();
            }
        });
        timer1.start();
        timer2 = new Timer(60000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                passou60Seg = true;
                run();
            }
        });
        this.portaSerial = portaSerial;
    }

    @Override
    public void run() {
        if (passou60Seg == true && requisitarDados == true && terminouRequisicao == true) {
            passou60Seg = false;
            terminouRequisicao = false;
            try {
                portaSerial.enviarRequisicaoNo();
            } catch (IOException | SQLException | InterruptedException ex ) {
            }
            terminouRequisicao = true;

        }
    }

    public void setRequisitarDados() {
        if (terminouRequisicao == true) {
            if (requisitarDados) {
                requisitarDados = false;
            } else {
                requisitarDados = true;
            }
        }
    }

    public boolean getRequisitarDados() {
        return requisitarDados;
    }

    public boolean getTerminouRequisicao() {
        return terminouRequisicao;
    }
}
